package com.mdxq.mall.user.service.impl;

import cn.hutool.core.util.StrUtil;
import com.mdxq.mall.user.entity.RoleMenuRelation;
import com.mdxq.mall.user.entity.RoleResourceRelation;
import com.mdxq.mall.user.mapper.RoleMenuRelationMapper;
import com.mdxq.mall.user.mapper.RoleResourceRelationMapper;
import com.mdxq.mall.user.service.RoleMenuRelationService;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.mdxq.mall.user.entity.Role;
import com.mdxq.mall.user.mapper.RoleMapper;
import com.mdxq.mall.user.service.RoleService;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 后台用户角色表 服务层实现。
 *
 * @author zxr
 * @since 2025-01-12
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role>  implements RoleService{
    @Autowired
    private RoleMenuRelationMapper relationMapper;
    @Override
    @Transactional // 事务声明的注解，所有的数据库操作满足原子性，要么都成功，要么都失败
    public boolean allocMenu(Long roleId, String menuIds) {
        //先删除已有的
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("role_id",roleId);
        relationMapper.deleteByQuery(queryWrapper);
        // 在批量插入本次的
        if(StrUtil.isNotBlank(menuIds)){
            List<RoleMenuRelation> relationList = new ArrayList<>();
            for (String menuId : menuIds.split(",")) {
                relationList.add(new RoleMenuRelation(null,roleId,Long.valueOf(menuId)));
            }
            relationMapper.insertBatch(relationList);
        }

        return true;
    }

    @Autowired
    private RoleResourceRelationMapper relationMapper2;
    @Override
    @Transactional
    public boolean allocResource(Long roleId, String resourceIds) {
        //先删除已有的
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("role_id",roleId);
        relationMapper2.deleteByQuery(queryWrapper);
        // 在批量插入本次的
        if(StrUtil.isNotBlank(resourceIds)){
            List<RoleResourceRelation> relationList = new ArrayList<>();
            for (String resourceId : resourceIds.split(",")) {
                relationList.add(new RoleResourceRelation(null,roleId,Long.valueOf(resourceId)));
            }
            relationMapper2.insertBatch(relationList);
        }
        return true;
    }
}
